package com.sync.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sync.platform.entity.SyncTask;
import com.sync.platform.entity.SyncTaskLog;
import com.sync.platform.mapper.SyncTaskLogMapper;
import com.sync.platform.mapper.SyncTaskMapper;
import com.sync.platform.service.SyncTaskLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Synchronization task log service implementation
 */
@Service
public class SyncTaskLogServiceImpl extends ServiceImpl<SyncTaskLogMapper, SyncTaskLog> implements SyncTaskLogService {

    @Autowired
    private SyncTaskMapper syncTaskMapper;

    @Override
    public List<SyncTaskLog> getLogsByTaskId(Long taskId) {
        LambdaQueryWrapper<SyncTaskLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SyncTaskLog::getTaskId, taskId);
        queryWrapper.orderByDesc(SyncTaskLog::getCreateTime);
        return list(queryWrapper);
    }

    @Override
    public List<SyncTaskLog> getRecentLogs(int limit) {
        LambdaQueryWrapper<SyncTaskLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(SyncTaskLog::getCreateTime);
        queryWrapper.last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public Long createLog(Long taskId, Integer taskType, String message, Integer status) {
        SyncTask syncTask = syncTaskMapper.selectById(taskId);
        if (syncTask == null) {
            throw new IllegalArgumentException("Task not found with id: " + taskId);
        }

        SyncTaskLog log = new SyncTaskLog();
        log.setTaskId(taskId);
        log.setTaskName(syncTask.getName());
        log.setTaskType(taskType);
        log.setStartTime(LocalDateTime.now());
        log.setStatus(status);
        log.setMessage(message);
        log.setSyncCount(0);

        save(log);
        return log.getId();
    }

    @Override
    public boolean updateLog(Long logId, Integer status, Integer syncCount, String message, String detailLog) {
        return lambdaUpdate()
                .eq(SyncTaskLog::getId, logId)
                .set(SyncTaskLog::getStatus, status)
                .set(SyncTaskLog::getSyncCount, syncCount)
                .set(SyncTaskLog::getMessage, message)
                .set(SyncTaskLog::getDetailLog, detailLog)
                .set(SyncTaskLog::getEndTime, LocalDateTime.now())
                .update();
    }

    @Override
    public int countLogsBetween(LocalDateTime startTime, LocalDateTime endTime) {
        return Math.toIntExact(lambdaQuery()
                .between(SyncTaskLog::getStartTime, startTime, endTime)
                .count());
    }

    /**
     * Calculate duration between start and end time in milliseconds
     *
     * @param startTime Start time
     * @param endTime End time
     * @return Duration in milliseconds
     */
    private Long calculateDuration(LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime == null || endTime == null) {
            return 0L;
        }
        return java.time.Duration.between(startTime, endTime).toMillis();
    }
}
